package com.zhong.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.zhong.subject.common.entity.PageResult;
import com.zhong.subject.common.enums.IsDeleteFlagEnum;
import com.zhong.subject.domain.bo.SubjectInfoBO;
import com.zhong.subject.domain.bo.SubjectOptionBO;
import com.zhong.subject.domain.convert.SubjectInfoConverter;
import com.zhong.subject.domain.handler.subject.SubjectTypeHandler;
import com.zhong.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.zhong.subject.domain.service.SubjectInfoDomainService;
import com.zhong.subject.infra.basic.entity.SubjectInfo;
import com.zhong.subject.infra.basic.entity.SubjectMapping;
import com.zhong.subject.infra.basic.service.SubjectInfoService;
import com.zhong.subject.infra.basic.service.SubjectLabelService;
import com.zhong.subject.infra.basic.service.SubjectMappingService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Service
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    /**
     * 题目新增外和mapping新增
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.subjectInfoBO：{}", JSON.toJSONString(subjectInfoBO));
        }
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDelete(IsDeleteFlagEnum.UN_DELETE.getCode());
        //这里透传，将subjectInfo传入并增加了id
        subjectInfoService.insert(subjectInfo);
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(Integer.parseInt(subjectInfo.getSubjectType()));
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        List<SubjectMapping> subjectMappingList = getSubjectMappings(subjectInfoBO);
        subjectMappingService.batchInsert(subjectMappingList);
    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.getSubjectPage.subjectInfoBO：{}", JSON.toJSONString(subjectInfoBO));
        }
        PageResult<SubjectInfoBO> subjectInfoBOPageResult = new PageResult<>();
        subjectInfoBOPageResult.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoBOPageResult.setPageSize(subjectInfoBO.getPageSize());
        int pageStart = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        Integer count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if (count == 0) {
            return subjectInfoBOPageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId(), pageStart, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConverter.INSTANCE.convertInfoListToBoList(subjectInfoList);
        subjectInfoBOPageResult.setRecords(subjectInfoBOList);
        subjectInfoBOPageResult.setTotal(count);
        return subjectInfoBOPageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.querySubjectInfo.subjectInfoBO：{}", JSON.toJSONString(subjectInfoBO));
        }
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        Preconditions.checkNotNull(subjectInfo,"为查询到该题目信息");

        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(Integer.parseInt(subjectInfo.getSubjectType()));
        SubjectOptionBO subjectOptionBO = handler.query(subjectInfo.getId());
        SubjectInfoBO infoBO = SubjectInfoConverter.INSTANCE.convertOptionBoAndInfoToInfoBo(subjectOptionBO, subjectInfo);
        List<String> labelNameList = new ArrayList<>();
        //查询subjectId对应的labels
        List<Long> labelIdList = subjectMappingService.queryLabelIdsBySubjectId(infoBO.getId());
        //通过labels查询所有的labelNames
        if (!labelIdList.isEmpty()) {
            labelIdList.forEach(id->{
                String labelName = subjectLabelService.queryById(id).getLabelName();
                if (labelName != null){
                    labelNameList.add(labelName);
                }else {
                    log.error("SubjectInfoDomainServiceImpl.querySubjectInfo: {}","查询labelId为" + id + "的name为空");
                }
            });
        }
        infoBO.setLabelNames(labelNameList);
        return infoBO;
    }

    /**
     * 将subjectInfoBO组装成SubjectMappingList
     */
    private static List<SubjectMapping> getSubjectMappings(SubjectInfoBO subjectInfoBO) {
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappingList = new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfoBO.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDelete(IsDeleteFlagEnum.UN_DELETE.getCode());
                subjectMappingList.add(subjectMapping);
            });
        });
        return subjectMappingList;
    }
}
